package com.ndood.core.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;

import org.apache.commons.lang3.StringUtils;

/**
 * 图片下载工具类
 */
public class ImageDownloadUtil {
	public static byte[] readInputStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		// 创建一个Buffer字符串
		byte[] buffer = new byte[1024];
		// 每次读取的字符串长度，如果为-1，代表全部读取完毕
		int len = 0;
		// 使用一个输入流从buffer里把数据读取出来
		while ((len = inStream.read(buffer)) != -1) {
			// 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
			outStream.write(buffer, 0, len);
		}
		// 关闭输入流
		inStream.close();
		// 把outStream里的数据写入内存
		return outStream.toByteArray();
	}

	public static void download(String dir, String address, String filename, String suffix) {
		// new一个文件对象用来保存图片，默认保存当前工程根目录
		File imageFile = new File(dir + File.separator + filename + suffix);
		if (imageFile.exists()) {
			return;
		}
		try {
			// new一个URL对象
			URL url = new URL(address);
			// 打开链接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			// 设置请求方式为"GET"
			conn.setRequestMethod("GET");
			// 超时响应时间为5秒
			conn.setConnectTimeout(5 * 1000);
			// 通过输入流获取图片数据
			InputStream inStream = conn.getInputStream();
			// 得到图片的二进制数据，以二进制封装得到数据，具有通用性
			byte[] data = readInputStream(inStream);

			// 创建输出流
			FileOutputStream outStream = new FileOutputStream(imageFile);
			// 写入数据
			outStream.write(data);
			// 关闭输出流
			outStream.close();
		} catch (Exception e) {
			e.printStackTrace();
			try { // 超时重试一次
					// new一个URL对象
				URL url = new URL(address);
				// 打开链接
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				// 设置请求方式为"GET"
				conn.setRequestMethod("GET");
				// 超时响应时间为5秒
				conn.setConnectTimeout(5 * 1000);
				// 通过输入流获取图片数据
				InputStream inStream = conn.getInputStream();
				// 得到图片的二进制数据，以二进制封装得到数据，具有通用性
				byte[] data = readInputStream(inStream);
				// new一个文件对象用来保存图片，默认保存当前工程根目录
				FileOutputStream outStream = new FileOutputStream(imageFile);
				// 写入数据
				outStream.write(data);
				// 关闭输出流
				outStream.close();
			} catch (Exception e2) {
			}
		}
	}

	/**
	 * 根据饿了吗图片地址下载图片，并返回图片保存路径
	 */
	public static String downloadElemePicture(String name) {
		if(StringUtils.isBlank(name)||"null".equals(name.trim())){
			return "";
		}
		String address = doWithElemePicture(name);
		String rootPath = (String) PropertiesUtil.getProperties().get("imageRootPath");
		Calendar now = Calendar.getInstance();
		int year = now.get(Calendar.YEAR);
		int month = now.get(Calendar.MONTH) + 1;
		String savePath = rootPath + "/3/" + year + "/" + month + "/";
		File dir = new File(savePath);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		String newFileName = name;
		if (address.contains("jpeg")) {
			download(savePath, address, newFileName, ".jpg");
			return savePath + newFileName + ".jpg";
		} else {
			download(savePath, address, newFileName, ".png");
			return savePath + newFileName + ".png";
		}
	}

	/**
	 * 解析饿了么图片
	 * //fuss10.elemecdn.com/d/85/15995a32586701f3c184f422cf66apng.png?imageMogr
	 * /format/webp/thumbnail/!80x80r/gravity/Center/crop/80x80/
	 */
	private static String doWithElemePicture(String src) {
		if (src.endsWith("jpeg")) {
			String p1 = src.substring(0, 1);
			String p2 = src.substring(1, 3);
			String img = src.substring(3);
			String dest = "https://fuss10.elemecdn.com/" + p1 + "/" + p2 + "/" + img + ".jpeg";
			return dest;
		}
		if (src.endsWith("png")) {
			String p1 = src.substring(0, 1);
			String p2 = src.substring(1, 3);
			String img = src.substring(3);
			String dest = "https://fuss10.elemecdn.com/" + p1 + "/" + p2 + "/" + img + ".png";
			return dest;
		}
		return "";
	}

	/**
	 * 对图片进行压缩
	 */
	public static String compressPicture(String name, String srcPath, int w, int h) {
		if(StringUtils.isBlank(name)||"null".equals(name)){
			return "";
		}
		String rootPath = (String) PropertiesUtil.getProperties().get("imageRootPath");
		Calendar now = Calendar.getInstance();
		int year = now.get(Calendar.YEAR);
		int month = now.get(Calendar.MONTH) + 1;
		String savePath = rootPath + "/3/" + year + "/" + month + "/";
		File dir = new File(savePath);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		String newFileName = name + "c";
		String destPath = savePath + newFileName + ".jpg";
		if (srcPath.contains("png")) {
			destPath = savePath + newFileName + ".png";
		}
		try {
			new ImageCompress(srcPath, destPath).resize(w, h);
			return destPath;
		} catch (Exception e) {
			// TODO 解决有些jpg图片无法打开并压缩的问题 Numbers of source Raster bands and
			// source color space components do not match
			try {
				HighQualityImageUtil.resize(new File(srcPath), new File(destPath), w, 0.7f);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			return destPath;
		}
	}

	public static void main(String[] args) throws Exception {
		/*
		 * String dest =
		 * doWithElemePicture("13665fc2143de142c2f7435f52589e35jpeg"); String
		 * dest2 = doWithElemePicture("d7e0be7e5420e213ea42e4fa3efa762bpng");
		 * System.out.println(dest2);
		 */
		/*
		 * System.out.println(downloadElemePicture(
		 * "13665fc2143de142c2f7435f52589e35jpeg"));
		 * System.out.println(downloadElemePicture(
		 * "d7e0be7e5420e213ea42e4fa3efa762bpng"));
		 */
		/*
		 * String savePath = compressPicture(
		 * "images/16/2017/12/Sr79eYjTNnFPnWLj7V53x0XhP9yYvC.jpg", 30, 30);
		 */
		// System.out.println(savePath);
		//narrowAndFormateTransfer("images/16/2017/12/Sr79eYjTNnFPnWLj7V53x0XhP9yYvC.png", "images/16/2017/heh.png", 130, 130, "png");
	}

}
